import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { preloadAllAudio } from '@/lib/audio';

interface AudioSettings {
  enabled: boolean;
  volume: number;
  voiceEnabled: boolean;
  voiceVolume: number;
}

interface AudioContextType {
  settings: AudioSettings;
  updateSettings: (newSettings: Partial<AudioSettings>) => void;
  isAudioReady: boolean;
}

const AudioContext = createContext<AudioContextType | undefined>(undefined);

interface AudioProviderProps {
  children: ReactNode;
}

// 默认音频设置
export const defaultAudioSettings: AudioSettings = {
  enabled: true,
  volume: 0.2,
  voiceEnabled: false, // 默认关闭语音提示
  voiceVolume: 0.5
};

export function AudioProvider({ children }: AudioProviderProps) {
  const [settings, setSettings] = useState<AudioSettings>(() => {
    // 从localStorage加载用户设置
    try {
      const saved = localStorage.getItem('audio-settings');
      if (saved) {
        return { ...defaultAudioSettings, ...JSON.parse(saved) };
      }
    } catch (error) {
      console.warn('加载音频设置失败:', error);
    }
    return defaultAudioSettings;
  });
  
  const [isAudioReady, setIsAudioReady] = useState(false);

  // 预加载音频文件
  useEffect(() => {
    const loadAudio = async () => {
      try {
        await preloadAllAudio();
        setIsAudioReady(true);
      } catch (error) {
        console.warn('音频预加载失败:', error);
        setIsAudioReady(true); // 即使预加载失败也标记为就绪
      }
    };

    loadAudio();
  }, []);

  // 保存设置到localStorage
  useEffect(() => {
    try {
      localStorage.setItem('audio-settings', JSON.stringify(settings));
    } catch (error) {
      console.warn('保存音频设置失败:', error);
    }
  }, [settings]);

  const updateSettings = (newSettings: Partial<AudioSettings>) => {
    setSettings(prev => ({ ...prev, ...newSettings }));
  };

  const value: AudioContextType = {
    settings,
    updateSettings,
    isAudioReady
  };

  return (
    <AudioContext.Provider value={value}>
      {children}
    </AudioContext.Provider>
  );
}

export function useAudio() {
  const context = useContext(AudioContext);
  if (context === undefined) {
    throw new Error('useAudio must be used within an AudioProvider');
  }
  return context;
}